//
//  ModifyNameAgeSexPage.swift
//  ReportScan
//
//  Created by woniu on 2025/9/12.
//修改姓名，性别，年龄

import Foundation
import SwiftUI

struct ModifyNameAgeSexPage: View {
    @State var currentIndex = 0
    @State var reportImgFolderURL:URL?
    @State var saveFolderURL:URL?
    
    var body: some View {
        Text("批量修改报告中的指定信息，如果未选择新文件存放位置，则新文件会替换旧文件")
        
        VStack(alignment: .leading) {
            HStack(alignment: .top){
                Button(role: .none) {
                    onChoseImageFolder()
                } label: {
                    Text("选择报告所在文件夹")
                }
                Text("第\(currentIndex)条")
               
                Button(role: .none) {
                    onChoseSaveFolder()
                } label: {
                    Text("新文件存放位置")
                }
                Button(role: .none) {
                    if let url = self.reportImgFolderURL{
                        to_deepModify(filePath: url)
                    }
                } label: {
                    Text("开始生成")
                }
                
            }.frame(height: 60)
            Divider()
        }
        .padding()
        Spacer()
    }
    
    //导入报告图片（递归搜索）
    private func onChoseImageFolder(){
        let openPanel = NSOpenPanel()
        openPanel.title = "选择报告文件"
        openPanel.showsHiddenFiles = false
        openPanel.allowsMultipleSelection = false
        openPanel.canChooseDirectories = true
        openPanel.canCreateDirectories = true
        
        openPanel.begin {result in
            if result == .OK, let url = openPanel.url {
                self.currentIndex = 0
                self.reportImgFolderURL = url
                print("报告图片位置:\(url)")
            }
        }
    }
    
    //选择存放位置
    private func onChoseSaveFolder(){
        let openPanel = NSOpenPanel()
        openPanel.title = "选择存放位置"
        openPanel.showsHiddenFiles = false
        openPanel.allowsMultipleSelection = false
        openPanel.canChooseDirectories = true
        openPanel.canCreateDirectories = true
        
        openPanel.begin {result in
            if result == .OK, let url = openPanel.url {
                print("存放位置:\(url)")
                self.saveFolderURL = url
            }
        }
    }
    
    //批量修改报告信息，从CSV获取
    public func to_deepModify(filePath:URL) {
        let fileManager = FileManager.default
        do {
            // 获取目录中的所有项目
            let contents = try fileManager.contentsOfDirectory(
                at: filePath,
                includingPropertiesForKeys: [.isDirectoryKey],
                options: [.skipsHiddenFiles]
            )
            let tempName = filePath.deletingLastPathComponent()
            print("\(tempName)共\(contents.count)个文件or文件夹")
            
            // 遍历每个项目
            for itemURL in contents {
                let resourceValues = try itemURL.resourceValues(forKeys: [.isDirectoryKey])
                // 判断是否为目录
                if let isDirectory = resourceValues.isDirectory, isDirectory {
                    // 如果是目录，则递归遍历
                    to_deepModify(filePath: itemURL)
                } else {
                    // 如果是文件，则直接处理
                    self.currentIndex += 1
                   
                    if let reportImg = loadImage(from: itemURL){

                        DrawImgService.modifyName_gender_age(reportImg: reportImg, name: "张传玉", age: 66, gender: "女") { newImg in
                            //存放到指定位置存放
                            if let cacheUrl = self.saveFolderURL{
                                
                                let fileName = itemURL.lastPathComponent
                                let savePath = cacheUrl.path + "/\(fileName)"
                                print("存放到:\(savePath)")
                                let _ = newImg.saveImage(to: URL.init(filePath: savePath))
                                
                            }else{
                                //替换文件
                                try? fileManager.removeItem(at: itemURL)
                                let savePath = itemURL.path
                                print("替换文件:\(savePath)")
                                let _ = newImg.saveImage(to: URL.init(filePath: savePath))
                            }
                           
                        }
                    }
                }
            }
        } catch {
            print("遍历目录时出错: \(error)")
        }
    }
    
    func loadImage(from url: URL) -> NSImage? {
        guard FileManager.default.fileExists(atPath: url.path()) else {
            print("图片文件不存在")
            return nil
        }
        guard let image = NSImage(contentsOf: url) else {
            print("无法加载图片")
            return nil
        }
        return image
    }
}

#Preview {
    ModifyReportPage()
}
